import { Body, Controller, Get, Post, Request, Session } from '@nestjs/common';
import { AccountDto } from '../dto/account.dto';
import { Md5Service } from '../services/md5.service';
import { AccountService } from '../services/account.service';
import { IBaseDto } from '../../base/interface/basedto.interface';
import { PositionService } from '../../address/services/position.service';
import { IAccount } from '../interface/account.interface';
import { BaseService } from '../../base/services/base.service';

@Controller('account')
export class AccountController {

  constructor(
    private readonly accountService: AccountService,
    private readonly positionService: PositionService,
    private readonly baseService: BaseService,
    private readonly md5Service: Md5Service
  ) { }

  @Post('sign')
  async sign(@Body() accountDto: AccountDto, @Request() req): Promise<IBaseDto> {
    const accountInfo = await this.accountService.getAccountByName(accountDto.accountName);
    const params = {
      accountDto,
      req,
      accountInfo
    };
    return null !== accountInfo ? await this.login(params) : await this.register(params);
  }

  @Get('logout')
  async logout(@Session() session): Promise<IBaseDto> {
    delete session.accountId;
    const outDto: IBaseDto = {
      status: 0,
      type: 'LOGOUT_SUCCESS',
      message: '退出成功'
    };
    return outDto;
  }

  async login(params): Promise<IBaseDto> {
    const { accountDto, accountInfo } = params;
    let outDto: IBaseDto = null;
    const password = await this.md5Service.passwordForMd5(accountDto.password);
    if (password === accountInfo.password) {
      outDto = {
        status: 0,
        type: 'LOGIN_SUCCESS',
        message: '管理员登录成功',
        data: accountInfo
      };
    } else {
      outDto = {
        status: 1,
        type: 'ERROR_PASSWORD',
        message: '该用户已存在，密码输入错误'
      };
    }
    return outDto;
  }

  async register(params): Promise<IBaseDto> {
    const { accountDto, req } = params;
    let outDto: IBaseDto = null;
    const password = await this.md5Service.passwordForMd5(accountDto.password);
    const id = await this.baseService.getId('account_id');
    const cityInfo = await this.positionService.getLocationForIp(req);
    const account: IAccount = {
      id,
      account_name: accountDto.accountName,
      password,
      admin: accountDto.admin || false,
      create_city: cityInfo.city
    };
    await this.accountService.createAccount(account);
    return outDto = {
      status: 0,
      type: 'REGISTER_SUCCESS',
      message: '注册成功',
      data: await this.accountService.getAccountByName(accountDto.accountName)
    };
  }

}